package com.dep.service;

import java.util.Collection;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.stereotype.Service;

/****
		 *消息推送管理 
		 * @author xiaoyou11@hotmail.com
		 *
 */
@Service
@RemoteProxy(name="MessagePush")
public class MessagePush {
	
	/****
			 * 页面加载时与服务端建立连接（如果需要用用户id标识的话）
			 * @param userId
	 */
	@RemoteMethod
	 public void onPageLoad(String userId) {
			
         //ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
         //scriptSession.setAttribute("userId", userId);
       /*  DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
         try {
                dwrScriptSessionManagerUtil.init();
         } catch (ServletException e) {
                e.printStackTrace();
         }*/
  }
	
	/****
			 * 服务端发送消息，调用前端的JavaScript方法
			 * @param post
			 * @return
	 */
	public void sendMessageAuto( Object post){
		//final String userId = "001";
		final Object __p = post;
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			@Override
			public boolean match(ScriptSession session) {
				/*if(session.getAttribute("userId") == null){
					return false;
				}else{
					return session.getAttribute("userId").equals(userId);
				}*/
				return true;
			}
		}, new Runnable() {
				private ScriptBuffer script = new ScriptBuffer();
				@Override
				public void run() {
					script.appendCall("setData", __p);
					Collection<ScriptSession> sessions = Browser.getTargetSessions();
					for(ScriptSession scriptSession : sessions){
						scriptSession.addScript(script);
					}
				}
			});
	}
}
